$(function() {
	window.mainpage.initMainLayout();
	window.mainpage.bindNavTabsButtonEvent();
	window.mainpage.bindMainTabsButtonEvent();
	window.mainpage.instTimerSpan();
	window.mainpage.initMenu();
	
	
});

(function($) {
	$.util.namespace("mainpage");
	$.util.namespace("mainpage.mainTabs");

	var homePageTitle = "主页", mainLayout = "#mainLayout", westLayout = "#westLayout", 
	menu_category = "#menu_category", menu_item = "#menu_item", 
	btnFullScreen = "#btnFullScreen", mainTabs = "#mainTabs";
	
	/**
	 * 初始化页面布局框架
	 */
	window.mainpage.initMainLayout = function() {
		$.util.exec(function () {
			var layout = $(mainLayout) ;
			layout.layout("collapse", "east");
			
			$(westLayout).layout("resize");
	    });
	};
	
	/**
	 * 绑定点击事件
	 */
	window.mainpage.bindNavTabsButtonEvent = function () {
        $("#btoHideWest").click(function () { window.mainpage.hideWest(); });
        $("#btoHideEast").click(function () { window.mainpage.hideEast(); });
        
        //隐藏顶部
    	$("#btnHideNorth").click(function () { window.mainpage.hideNorth(); });
    	//显示顶部
    	var btnShow = $("#btnShowNorth").click(function () { window.mainpage.showNorth(); });
    	//全屏
    	$(btnFullScreen).click(function () {
            if ($.util.supportsFullScreen) {
                if ($.util.isFullScreen()) {
                    $.util.cancelFullScreen();
                } else {
                    $.util.requestFullScreen();
                }
            } else {
                $.easyui.messager.show("当前浏览器不支持全屏 API，请更换至最新的 Chrome/Firefox/Safari 浏览器或通过 F11 快捷键进行操作。");
            }
        });
        
    };

    window.mainpage.hideNorth = function () { $(mainLayout).layout("collapse", "north"); };
    window.mainpage.showNorth = function () { $(mainLayout).layout("expand", "north"); };
    window.mainpage.hideWest = function () { $(mainLayout).layout("collapse", "west"); };
    window.mainpage.hideEast = function () { $(mainLayout).layout("collapse", "east"); };
    
    window.mainpage.bindMainTabsButtonEvent = function () {
    	$("#mainTabs_toggleAll").click(function () { window.mainpage.togglePanels(); });
        $("#mainTabs_jumpHome").click(function () { window.mainpage.mainTabs.jumpHome(); });
        $("#mainTabs_jumpTab").click(function () { window.mainpage.mainTabs.jumpTab(); });
        $("#mainTabs_closeTab").click(function () { window.mainpage.mainTabs.closeCurrentTab(); });
        $("#mainTabs_closeOther").click(function () { window.mainpage.mainTabs.closeOtherTabs(); });
        $("#mainTabs_closeLeft").click(function () { window.mainpage.mainTabs.closeLeftTabs(); });
        $("#mainTabs_closeRight").click(function () { window.mainpage.mainTabs.closeRightTabs(); });
        $("#mainTabs_closeAll").click(function () { window.mainpage.mainTabs.closeAllTabs(); });
    };
    window.mainpage.togglePanels = function () { $(mainLayout).layout("toggleAll", "collapse"); };
	
	/**
	 * 时钟
	 */
	window.mainpage.instTimerSpan = function () {
        var timerSpan = $("#timerSpan"), interval = function () { timerSpan.text($.date.format(new Date(), "yyyy年MM月dd日 HH:ss:mm")); };
        interval();
        window.setInterval(interval, 1000);
    };

	/**
	 * 初始化菜单
	 */
	window.mainpage.initMenu = function() {
		window.mainpage.loadMenu(function(ul, menus) {
			var list = ul.find("a");
			if (!list.length) {
				return;
			}
			// 默认选中Menu，没有指定则选择第一个Menu
			var defaultIndex = 0;
			$.each(menus, function(i, item) {
				if (item.defaultSelect) {
					defaultIndex = i;
					return;
				}
			});
			list.eq(defaultIndex).click();

		});
	};

	/**
	 * 加载菜单分类 callback: 为一个 Function 对象；表示加在完成菜单数据后调用的回调函数
	 */
	window.mainpage.loadMenu = function(callback) {
		var menuCategory = $(menu_category).empty();

		$.get("/blue-web-admin-easyui/data/menu_category.json", function(menus) {
			$.each(window.mainpage.navMenusData = menus,function(i, item) {
				var _li = $("<li></li>").appendTo(menuCategory);
				var _div = $("<div></div>").addClass("panel-header panel-header-noborder").appendTo(_li);
				var _a = $("<a></a>").attr({href : "javascript:void(0);", target : "_self"})
				.hover(function() {
					_a.addClass("tree-node-selected");
				},function() {
					if (!_a.hasClass("selected")) {$(this).removeClass("tree-node-selected");}
				}).click(function() {
					if (_a.is(".tree-node-selected.selected")|| _a.attr("disabled")) {return;}
					menuCategory.find("a").removeClass("tree-node-selected selected");
					_a.addClass("tree-node-selected selected");
					
					//加载菜单项
					window.mainpage.initMenuNavTree(item.id);
					
				}).appendTo(_div);

				_a.html('<i class="'+item.icon+' icon fa-lg" style="color:'+item.color+'"></i><span class="text">'+item.fullName+'</span>');
			});

			var layout = $(westLayout), south = layout.layout("panel", "south"), 
			southOpts = south.panel("options"), 
			border = south.panel("panel").border("top"),
			navHeight = 27;
			
			southOpts.minHeight = border + Math.min(menus.length, 6) * navHeight;
			southOpts.maxHeight = border + menus.length * navHeight;

			layout.layout("resize");

			if ($.isFunction(callback)) {
				callback.call(this, menuCategory, menus);
			}
		});
	}
	
	window.mainpage.initMenuNavTree = function(cid) {
		var t = window.mainpage.loadMenuNavTree(), root = $.extend({}, $.array.first(window.mainpage.navMenusData, function (val) { return val.id == cid; })); ;
		
		$.get("/blue-web-admin-easyui/data/menu_item.json", {"cid": cid}, function(result) {
			root.children = $.array.likeArrayNotString(result) ? result : [];
			t.tree("loadData", [root]);
		}, "JSON");
		
	}
	window.mainpage.loadMenuNavTree = function() {
		var menuItem = $(menu_item).empty() ;
		var t = $("<ul></ul>").appendTo(menuItem) ;
		t.tree({
			animate: true,
            lines: true,
            toggleOnClick: true,
            onClick: function (node) {
            	if(undefined != node.attributes) {
            		var href = node.attributes.url ;
            		if(undefined != href && "" != href.trim()){
            			node.attributes.href=href ;
            		}
            	}
                window.mainpage.mainTabs.addModuleTab(node);
            },
            onLoadSuccess: function(node, data) {
            	window.mainpage.instTreeStatus(this);
            }
		});
		return t ;
	};
	window.mainpage.instTreeStatus = function (target) {
        var t = $(target), array = t.tree("getRoots");
        $.each(array, function (i, n) {
            var cc = t.tree("getChildren", n.target);
            t.tree("expand", n.target);
            $.each(cc, function (l, c) { t.tree("collapseAll", c.target); });
        });
    };
	
	
	window.mainpage.mainTabs.addModuleTab = function(node) {
		var t = $(mainTabs) ;
		
		var opts = {title : "新建选项卡", href : "", iniframe : true, closable : true, selected : true}
		opts = $.extend(opts, node) ;
		opts.title = node.fullName ;
		
		if(t.tabs("exists", opts.title)) {//如果tab已经存在,则选中并刷新该tab
			t.tabs("select", opts.title);
		} else {
			if(opts.iniframe) {//iframe方式打开
				if(opts.href) {
					opts.location = opts.href ;
					opts.href = null;
		            opts.content = "<iframe class=\"panel-iframe\" frameborder=\"0\" width=\"100%\" src=\""+opts.location+"\" height=\"100%\" marginwidth=\"0px\" marginheight=\"0px\" scrolling=\"auto\"></iframe>";
		            
					window.mainpage.mainTabs.createTab(opts) ;
				}
			} else {//href方式打开
				if(opts.href) {
					opts.title = node.fullName ;
					window.mainpage.mainTabs.createTab(opts) ;
				}
			}
		}
	};
	
	window.mainpage.mainTabs.createTab = function(opts) {
		var t = $(mainTabs) ;
		/*opts.tools = [{
			iconCls: "icon-mini-refresh", 
			handler:function(){
				t.tabs("refresh");
			}
		}];*/
		t.tabs("add", opts);
	};
	
	window.mainpage.mainTabs.jumpHome = function () {
        var t = $(mainTabs), tabs = t.tabs("tabs"), panel = $.array.first(tabs, function (val) {
            var opts = val.panel("options");
            return opts.title == homePageTitle;
        });
        if (panel && panel.length) {
            var index = t.tabs("getTabIndex", panel);
            t.tabs("select", index);
        }
    };
	window.mainpage.mainTabs.jumpTab = function (which) { $(mainTabs).tabs("jumpTab", which); };
	window.mainpage.mainTabs.closeCurrentTab = function () {$(mainTabs).tabs("closeCurrent", homePageTitle);};
    window.mainpage.mainTabs.closeOtherTabs = function () {$(mainTabs).tabs("closeOther", homePageTitle);};
    window.mainpage.mainTabs.closeLeftTabs = function () {$(mainTabs).tabs("closeLeft", homePageTitle);};
    window.mainpage.mainTabs.closeRightTabs = function () {$(mainTabs).tabs("closeRight", homePageTitle);};
	window.mainpage.mainTabs.closeAllTabs = function() {$(mainTabs).tabs("closeAll", homePageTitle);};
	
})(jQuery);
